<template>
	<view class="container">
		<view v-if="loading" class="loading">
			<text>加载中...</text>
		</view>
		
		<block v-else>
			<view class="status-section">
				<view class="status-icon" :class="getStatusClass(order.status)">
					<text class="iconfont" :class="getStatusIcon(order.status)"></text>
				</view>
				<view class="status-info">
					<view class="status-text">{{ getStatusText(order.status) }}</view>
					<view class="status-desc">{{ getStatusDesc(order.status) }}</view>
				</view>
			</view>
			
			<!-- 收货地址 -->
			<view class="card-section">
				<view class="section-header">
					<text class="iconfont icon-location"></text>
					<text>收货地址</text>
				</view>
				<view class="address-content" v-if="order.addressInfo">
					<view class="address-user">
						<text class="user-name">{{ order.addressInfo.receiverName }}</text>
						<text class="user-phone">{{ order.addressInfo.receiverPhone }}</text>
					</view>
					<view class="address-detail">{{ order.addressInfo.detailedAddress }}</view>
				</view>
				<view class="address-content" v-else>
					<text class="no-data">暂无地址信息</text>
				</view>
			</view>
			
			<!-- 订单信息 -->
			<view class="card-section">
				<view class="section-header">
					<text class="iconfont icon-order"></text>
					<text>订单信息</text>
				</view>
				<view class="info-content">
					<view class="info-item">
						<text class="info-label">订单编号</text>
						<text class="info-value">{{ order.orderNo }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">创建时间</text>
						<text class="info-value">{{ formatDate(order.createTime) }}</text>
					</view>
					<view class="info-item" v-if="order.paymentTime">
						<text class="info-label">支付时间</text>
						<text class="info-value">{{ formatDate(order.paymentTime) }}</text>
					</view>
					<view class="info-item" v-if="order.shippingTime">
						<text class="info-label">发货时间</text>
						<text class="info-value">{{ formatDate(order.shippingTime) }}</text>
					</view>
					<view class="info-item" v-if="order.completionTime">
						<text class="info-label">完成时间</text>
						<text class="info-value">{{ formatDate(order.completionTime) }}</text>
					</view>
					<view class="info-item" v-if="order.cancellationTime">
						<text class="info-label">取消时间</text>
						<text class="info-value">{{ formatDate(order.cancellationTime) }}</text>
					</view>
					<view class="info-item">
						<text class="info-label">支付方式</text>
						<text class="info-value">{{ paymentTypeText }}</text>
					</view>
					<view class="info-item" v-if="order.remark">
						<text class="info-label">订单备注</text>
						<text class="info-value">{{ order.remark }}</text>
					</view>
				</view>
			</view>
			
			<!-- 配送信息 -->
			<view class="card-section" v-if="order.delivery">
				<view class="section-header">
					<text class="iconfont icon-truck"></text>
					<text>配送信息</text>
				</view>
				<view class="info-content">
					<view class="info-item">
						<text class="info-label">配送状态</text>
						<text class="info-value">
							<text class="delivery-tag">{{ getDeliveryStatus(order.delivery.deliveryStatus) }}</text>
						</text>
					</view>
					<view class="info-item" v-if="order.delivery.riderId">
						<text class="info-label">配送人员</text>
						<text class="info-value">{{ order.delivery.riderName || '暂无' }}</text>
					</view>
					<view class="info-item" v-if="order.delivery.riderPhone">
						<text class="info-label">联系电话</text>
						<text class="info-value">{{ order.delivery.riderPhone }}</text>
					</view>
					<view class="info-item" v-if="order.delivery.pickupTime">
						<text class="info-label">取件时间</text>
						<text class="info-value">{{ formatDate(order.delivery.pickupTime) }}</text>
					</view>
					<view class="info-item" v-if="order.delivery.estimatedDeliveryTime">
						<text class="info-label">预计送达</text>
						<text class="info-value">{{ formatDate(order.delivery.estimatedDeliveryTime) }}</text>
					</view>
					<view class="info-item" v-if="order.delivery.actualDeliveryTime">
						<text class="info-label">实际送达</text>
						<text class="info-value">{{ formatDate(order.delivery.actualDeliveryTime) }}</text>
					</view>
					<view class="info-item" v-if="order.delivery.deliveryNote">
						<text class="info-label">配送备注</text>
						<text class="info-value">{{ order.delivery.deliveryNote }}</text>
					</view>
				</view>
			</view>
			
			<!-- 商品列表 -->
			<view class="card-section">
				<view class="section-header">
					<text class="iconfont icon-goods"></text>
					<text>商品信息</text>
				</view>
				<view class="products-content">
					<view v-for="(item, index) in order.orderItems" :key="index" class="product-item">
						<image 
							:src="getImgUrl(item.image && item.image.length > 0 ? item.image[0] : '')" 
							class="product-image"
							mode="aspectFill"
						></image>
						<view class="product-info">
							<text class="product-name">{{ item.commodityName }}</text>
							<view class="product-price-qty">
								<text class="product-price">¥{{ item.commodityPrice }}</text>
								<text class="product-qty">x{{ item.quantity }}</text>
							</view>
						</view>
					</view>
				</view>
				
				<view class="price-detail">
					<view class="price-item">
						<text class="price-label">商品总额</text>
						<text class="price-value">¥{{ order.totalAmount || 0 }}</text>
					</view>
					<view class="price-item">
						<text class="price-label">运费</text>
						<text class="price-value">+¥{{ order.freight || 0 }}</text>
					</view>
					<view class="price-item" v-if="order.discount">
						<text class="price-label">优惠</text>
						<text class="price-value discount">-¥{{ order.discount }}</text>
					</view>
					<view class="price-item total">
						<text class="price-label">实付金额</text>
						<text class="price-value">¥{{ order.actualAmount || 0 }}</text>
					</view>
				</view>
			</view>
			
			<!-- 支付信息 -->
			<view class="card-section" v-if="order.payment">
				<view class="section-header">
					<text class="iconfont icon-pay"></text>
					<text>支付信息</text>
				</view>
				<view class="info-content">
					<view class="info-item">
						<text class="info-label">支付状态</text>
						<text class="info-value">
							<text class="payment-tag" :class="{'success': order.payment.paymentStatus === 'SUCCESS'}">
								{{ order.payment.paymentStatus === 'SUCCESS' ? '已支付' : '待支付' }}
							</text>
						</text>
					</view>
					<view class="info-item" v-if="order.payment.paymentNo">
						<text class="info-label">支付流水号</text>
						<text class="info-value">{{ order.payment.paymentNo }}</text>
					</view>
					<view class="info-item" v-if="order.payment.paymentPlatform">
						<text class="info-label">支付平台</text>
						<text class="info-value">{{ order.payment.paymentPlatform }}</text>
					</view>
					<view class="info-item" v-if="order.payment.paymentTime">
						<text class="info-label">支付时间</text>
						<text class="info-value">{{ formatDate(order.payment.paymentTime) }}</text>
					</view>
				</view>
			</view>
			
			<!-- 订单操作 -->
			<view class="order-actions" v-if="showActions">
				<button 
					v-if="order.status === 'PENDING_PAYMENT'" 
					class="action-btn primary"
					@click="payOrder"
				>去付款</button>
				
				<button 
					v-if="order.status === 'SHIPPED'" 
					class="action-btn primary"
					@click="completeOrder"
				>确认收货</button>
				
				<button 
					v-if="order.status === 'PENDING_PAYMENT'" 
					class="action-btn"
					@click="cancelOrder"
				>取消订单</button>
			</view>
		</block>
	</view>
</template>

<script>
import { SERVER_BASE_URL } from '@/utils/request';
import http from '@/utils/request';

export default {
	data() {
		return {
			orderNo: '',
			order: {},
			loading: true,
			userId: null,
			serverBaseUrl: SERVER_BASE_URL,
			showPay: false
		};
	},
	computed: {
		showActions() {
			return (this.order.status === 'PENDING_PAYMENT' || this.order.status === 'SHIPPED');
		},
		// 订单状态中文名称
		paymentTypeText() {
			const typeMap = {
				'ONLINE': '在线支付',
				'CASH': '货到付款'
			};
			return typeMap[this.order.paymentType] || this.order.paymentType || '未知';
		}
	},
	onLoad(options) {
		this.orderNo = options.orderNo;
		this.showPay = options.pay === '1';
		
		this.checkLoginStatus();
		
		if (this.orderNo) {
			this.getOrderDetail();
		} else {
			uni.showToast({
				title: '订单号不能为空',
				icon: 'none'
			});
			
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		}
	},
	methods: {
		// 检查登录状态
		checkLoginStatus() {
			const userStr = uni.getStorageSync('user');
			if (userStr) {
				try {
					const userInfo = JSON.parse(userStr);
					if (userInfo && userInfo.id) {
						this.userId = userInfo.id;
						return true;
					}
				} catch (error) {
					console.error('解析用户信息失败', error);
				}
			}
			
			uni.showToast({
				title: '请先登录',
				icon: 'none'
			});
			
			setTimeout(() => {
				uni.navigateTo({
					url: '/pages/login/login'
				});
			}, 1500);
			
			return false;
		},
		
		// 获取订单详情
		async getOrderDetail() {
			if (!this.checkLoginStatus()) return;
			
			this.loading = true;
			try {
				const response = await http.get(`/order/detail/${this.orderNo}`);
				
				if (response.code === 200) {
					this.order = response.data.order;
					
					// 整合订单项与配送信息
					if (response.data.items) {
						this.order.orderItems = response.data.items;
					}
					
					if (response.data.delivery) {
						this.order.delivery = response.data.delivery;
					}
					
					if (response.data.payment) {
						this.order.payment = response.data.payment;
					}
					
					// 如果需要显示支付页面
					if (this.showPay && this.order.status === 'PENDING_PAYMENT') {
						setTimeout(() => {
							this.payOrder();
						}, 500);
					}
				} else {
					uni.showToast({
						title: response.message || '获取订单详情失败',
						icon: 'none'
					});
				}
			} catch (error) {
				console.error('获取订单详情失败:', error);
				uni.showToast({
					title: '获取订单详情失败',
					icon: 'none'
				});
			} finally {
				this.loading = false;
			}
		},
		
		// 取消订单
		cancelOrder() {
			if (!this.checkLoginStatus()) return;
			
			uni.showModal({
				title: '提示',
				content: '确定要取消该订单吗？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const response = await http.put(`/order/cancel/${this.orderNo}`);
							
							if (response.code === 200) {
								uni.showToast({
									title: '订单取消成功',
									icon: 'success'
								});
								
								// 刷新订单详情
								this.getOrderDetail();
							} else {
								uni.showToast({
									title: response.message || '取消订单失败',
									icon: 'none'
								});
							}
						} catch (error) {
							console.error('取消订单失败:', error);
							uni.showToast({
								title: '取消订单失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		
		// 确认收货
		completeOrder() {
			if (!this.checkLoginStatus()) return;
			
			uni.showModal({
				title: '提示',
				content: '确认已收到商品？',
				success: async (res) => {
					if (res.confirm) {
						try {
							const response = await http.put(`/order/complete/${this.orderNo}`);
							
							if (response.code === 200) {
								uni.showToast({
									title: '确认收货成功',
									icon: 'success'
								});
								
								// 刷新订单详情
								this.getOrderDetail();
							} else {
								uni.showToast({
									title: response.message || '确认收货失败',
									icon: 'none'
								});
							}
						} catch (error) {
							console.error('确认收货失败:', error);
							uni.showToast({
								title: '确认收货失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		
		// 去支付
		payOrder() {
			if (!this.checkLoginStatus()) return;
			
			// 在实际应用中，这里应该调用支付接口或跳转到支付页面
			uni.showModal({
				title: '支付确认',
				content: `确认支付 ¥${this.order.actualAmount} 元？`,
				success: async (res) => {
					if (res.confirm) {
						try {
							const paymentInfo = {
								orderId: this.orderNo,
								paymentNo: 'WX' + new Date().getTime(),
								paymentPlatform: 'WECHAT'
							};
							
							const response = await http.put('/order/pay', paymentInfo);
							
							if (response.code === 200) {
								uni.showToast({
									title: '支付成功',
									icon: 'success'
								});
								
								// 刷新订单详情
								this.getOrderDetail();
							} else {
								uni.showToast({
									title: response.message || '支付失败',
									icon: 'none'
								});
							}
						} catch (error) {
							console.error('支付失败:', error);
							uni.showToast({
								title: '支付失败',
								icon: 'none'
							});
						}
					}
				}
			});
		},
		
		// 处理图片URL
		getImgUrl(url) {
			if (!url) return '/static/icons/no-image.png';
			
			// 确保有服务器地址前缀
			let fullUrl = url;
			if (url.startsWith('/uploads/')) {
				fullUrl = this.serverBaseUrl + url;
			}
			
			return fullUrl;
		},
		
		// 格式化日期
		formatDate(dateString) {
			if (!dateString) return '-';
			const date = new Date(dateString);
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
		},
		
		// 订单状态中文名称
		getStatusText(status) {
			const statusMap = {
				'PENDING_PAYMENT': '待付款',
				'PAID': '待发货',
				'SHIPPED': '待收货',
				'COMPLETED': '已完成',
				'CANCELLED': '已取消'
			};
			return statusMap[status] || status;
		},
		
		// 获取订单状态描述
		getStatusDesc(status) {
			const descMap = {
				'PENDING_PAYMENT': '请尽快完成支付',
				'PAID': '商家正在处理您的订单',
				'SHIPPED': '商品已发出，等待送达',
				'COMPLETED': '订单已完成，感谢您的购买',
				'CANCELLED': '订单已取消'
			};
			return descMap[status] || '';
		},
		
		// 获取配送状态文本
		getDeliveryStatus(status) {
			const statusMap = {
				'PENDING': '待分配',
				'ASSIGNED': '已分配',
				'PICKED': '已取件',
				'DELIVERED': '已送达'
			};
			return statusMap[status] || status || '暂无信息';
		},
		
		// 获取订单状态样式类名
		getStatusClass(status) {
			const classMap = {
				'PENDING_PAYMENT': 'pending',
				'PAID': 'paid',
				'SHIPPED': 'shipped',
				'COMPLETED': 'completed',
				'CANCELLED': 'cancelled'
			};
			return classMap[status] || '';
		},
		
		// 获取订单状态图标
		getStatusIcon(status) {
			const iconMap = {
				'PENDING_PAYMENT': 'icon-wallet',
				'PAID': 'icon-package',
				'SHIPPED': 'icon-truck',
				'COMPLETED': 'icon-check',
				'CANCELLED': 'icon-close'
			};
			return iconMap[status] || 'icon-order';
		},
		
		// 获取支付方式
		getPaymentMethod(method) {
			const methodMap = {
				'WECHAT_PAY': '微信支付',
				'ALIPAY': '支付宝',
				'BANK_CARD': '银行卡',
				'CASH_ON_DELIVERY': '货到付款'
			};
			return methodMap[method] || '未支付';
		},
		
		// 计算商品总价
		getProductTotal() {
			if (!this.order.orderItems) return 0;
			
			return this.order.orderItems.reduce((total, item) => {
				return total + (item.commodityPrice * item.quantity);
			}, 0).toFixed(2);
		}
	}
};
</script>

<style>
.container {
	background-color: #f5f5f5;
	min-height: 100vh;
	padding-bottom: 30rpx;
}

.loading {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 100rpx 0;
	color: #999;
	font-size: 30rpx;
}

/* 状态区域 */
.status-section {
	background-color: #409EFF;
	padding: 40rpx 30rpx;
	display: flex;
	align-items: center;
	color: #fff;
}

.status-icon {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	background-color: rgba(255, 255, 255, 0.2);
	display: flex;
	justify-content: center;
	align-items: center;
	margin-right: 20rpx;
}

.status-icon .iconfont {
	font-size: 40rpx;
}

.status-icon.pending {
	background-color: rgba(245, 158, 11, 0.2);
}

.status-icon.paid {
	background-color: rgba(230, 162, 60, 0.2);
}

.status-icon.shipped {
	background-color: rgba(64, 158, 255, 0.2);
}

.status-icon.completed {
	background-color: rgba(103, 194, 58, 0.2);
}

.status-icon.cancelled {
	background-color: rgba(245, 108, 108, 0.2);
}

.status-text {
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.status-desc {
	font-size: 26rpx;
	opacity: 0.8;
}

/* 卡片式区域 */
.card-section {
	background-color: #fff;
	margin: 20rpx;
	border-radius: 12rpx;
	overflow: hidden;
}

.section-header {
	padding: 20rpx;
	display: flex;
	align-items: center;
	border-bottom: 1rpx solid #eee;
}

.section-header .iconfont {
	font-size: 32rpx;
	color: #409EFF;
	margin-right: 10rpx;
}

.section-header text {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
}

/* 地址内容 */
.address-content {
	padding: 20rpx;
}

.address-user {
	display: flex;
	margin-bottom: 10rpx;
}

.user-name {
	font-size: 30rpx;
	font-weight: bold;
	color: #333;
	margin-right: 20rpx;
}

.user-phone {
	font-size: 28rpx;
	color: #666;
}

.address-detail {
	font-size: 28rpx;
	color: #666;
	line-height: 1.4;
}

.no-data {
	font-size: 28rpx;
	color: #999;
	display: flex;
	justify-content: center;
	padding: 20rpx 0;
}

/* 信息内容 */
.info-content {
	padding: 10rpx 20rpx;
}

.info-item {
	display: flex;
	justify-content: space-between;
	padding: 10rpx 0;
}

.info-label {
	font-size: 26rpx;
	color: #666;
}

.info-value {
	font-size: 26rpx;
	color: #333;
	max-width: 60%;
	text-align: right;
}

/* 标签样式 */
.delivery-tag, .payment-tag {
	background-color: #E6A23C;
	color: #fff;
	font-size: 24rpx;
	padding: 2rpx 10rpx;
	border-radius: 4rpx;
}

.payment-tag.success {
	background-color: #67C23A;
}

/* 商品列表 */
.products-content {
	padding: 10rpx 20rpx;
	border-bottom: 1rpx solid #f5f5f5;
}

.product-item {
	display: flex;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
}

.product-item:last-child {
	border-bottom: none;
}

.product-image {
	width: 120rpx;
	height: 120rpx;
	border-radius: 8rpx;
	background-color: #f5f5f5;
}

.product-info {
	flex: 1;
	margin-left: 20rpx;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.product-name {
	font-size: 26rpx;
	color: #333;
	line-height: 1.4;
	margin-bottom: 20rpx;
}

.product-price-qty {
	display: flex;
	justify-content: space-between;
}

.product-price {
	font-size: 28rpx;
	color: #F56C6C;
	font-weight: bold;
}

.product-qty {
	font-size: 24rpx;
	color: #999;
}

/* 价格详情 */
.price-detail {
	padding: 20rpx;
}

.price-item {
	display: flex;
	justify-content: space-between;
	padding: 10rpx 0;
}

.price-label {
	font-size: 26rpx;
	color: #666;
}

.price-value {
	font-size: 26rpx;
	color: #333;
}

.price-value.discount {
	color: #F56C6C;
}

.price-item.total {
	margin-top: 20rpx;
	padding-top: 20rpx;
	border-top: 1rpx solid #eee;
}

.price-item.total .price-label {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
}

.price-item.total .price-value {
	font-size: 32rpx;
	font-weight: bold;
	color: #F56C6C;
}

/* 订单操作 */
.order-actions {
	display: flex;
	justify-content: flex-end;
	margin: 30rpx 20rpx;
}

.action-btn {
	margin-left: 20rpx;
	font-size: 28rpx;
	padding: 0 40rpx;
	height: 70rpx;
	line-height: 70rpx;
	background-color: #fff;
	border: 1rpx solid #ddd;
	border-radius: 35rpx;
	color: #666;
}

.action-btn.primary {
	background-color: #409EFF;
	color: #fff;
	border: none;
}
</style> 